<?php

namespace app\admin\model;

use think\Model;
use think\Db;

class Returned extends Model
{

    

    

    // 表名
    protected $name = 'returned';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'good_json_text',
        'create_time_text',
        'returntime_text'
    ];

    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }
    public function getGoodJsonTextAttr($value, $data)
    {
        if($data){
            $return = json_decode($data['good_json'],true);
            foreach ($return as $key => $value) {
                $rugood_data = Db::name('rugood')->where('id',$value['rugood_id'])->find();
                $return[$key]['good_data'] = $rugood_data;

                $cangku_data = Db::name('cangku')->where('id',$rugood_data['cangku_id'])->find();
                $return[$key]['cangku_data'] = $cangku_data;
            }
            return $return;
        }
    }
    
            public function admin()
    {
        return $this->belongsTo('admin', 'user_id')->bind('nickname');
    }
 
    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            
            $good_array = json_decode($row['good_json'],true);

            foreach ($good_array as $key => $value) {

                $warehousing_data = Db::name('rugood')->where('id',$value['rugood_id'])->find();

                Db::name('rugood')->where(['sku'=>$warehousing_data['sku']])->setInc('return_num',$value['return_num']);
                Db::name('rugood')->where(['sku'=>$warehousing_data['sku']])->setDec('shengyu_num',$value['return_num']);
            }

            $row->getQuery()->where($pk, $row[$pk])->update(['return_order_no'=>'TH'.date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8)]
            );

        });
    }




    public function getReturntimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['returntime']) ? $data['returntime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setReturntimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


}
